<?php

class UserController extends \BaseController {

    public function postLogin() {
        $input = Input::all();

        //验证提交的数据
        $rules = array(
            'username' => 'required | min:4',
            'password' => 'required | min:6'
        );

        $validator = Validator::make($input, $rules);

        if($validator->fails()) {
            return $messages = $validator->messages();
        }

        $isRememberMe = isset($input['remember'])?true:false;

        if(Auth::attempt(array('username' => $input['username'], 'password' => $input['password']), $isRememberMe)||
           Auth::attempt(array('email' => $input['username'], 'password' => $input['password']), $isRememberMe)
          )
        {

            return 'login_success';
        }else {
            return 'login_error';
        }

    }

    public function postRegister() {
        $input = Input::all();

        //验证提交的数据
        $rules = array(
            'username' => 'required | min:4 | unique:users',
            'password' => 'required | min:6 | confirmed',
            'password_confirmation' => 'required',
            'email' => 'required | email | unique:users',
            'check-register' => 'accepted'
        );

        $validator = Validator::make($input, $rules);

        if($validator->fails()) {
            return $messages = $validator->messages();
        }


        $user = new User();
        $user->username = $input['username'];
        $user->email = $input['email'];
        $user->password = Hash::make($input['password']);
        $user->role = 4;
        $user->reg_date = time();
        $user->save();
        return "register_success";
    }

    public function getLogout() {
        Auth::logout();
		return Redirect::to('/');
    }

    //修改用户信息
    public function getEdit($id = '') {
        if(!Auth::check()) {
            return Redirect::to('/');
        }
        $userInfo = Auth::user();

		if($userInfo->role != 1 || $id == ''){
        	return View::make('front/user_edit')
                        ->with('userInfo', $userInfo);
		} else {
			$userInfo = User::find($id);
			$roles = Role::all();
			return View::make('front/user_edit_model')
                        ->with('userInfo', $userInfo)
						->with('roles', $roles);
		}
    }

    public function postEdit() {
        if(!Auth::check()) {
            return Redirect::to('/');
        }

        $userInfo = Auth::user();
        $inputData = Input::all();

		if($userInfo->role == 1 && isset($inputData['action']) && $inputData['action'] == 'admin_edit') {
			$userInfo = User::find($inputData['user_id']);


		}

        //数据验证
        $rules = array(
            'password' => 'min:6 | confirmed',
            'email' => 'required | email',
        );

        if($inputData['email'] != $userInfo->email) {
            $rules['email'] = 'required | email | unique:users';
        }

        $validator = Validator::make($inputData, $rules);

        if($validator->fails()) {
			if(isset($inputData['action']) && $inputData['action'] == 'admin_edit') {
            	return Redirect::to('/user/manage')->withErrors($validator);
			} else {
				return Redirect::to('/user/edit')->withErrors($validator);
			}
        }



        $user = User::find($userInfo->id);
        if($inputData['password'] != ''){
            $user->password = Hash::make($inputData['password']);
        }
        $user->firstname = $inputData['firstname'];
        $user->lastname = $inputData['lastname'];
        $user->email = $inputData['email'];
        //$user->avatar = $inputData['avatar'];
		if(isset($inputData['action']) && $inputData['action'] == 'admin_edit') {
			$user->role = $inputData['role'];
		}

        $user->description_me = $inputData['description_me'];
        $user->birthday = $inputData['birthday'];
        $user->sex = $inputData['sex'];

        $user->save();

		if(isset($inputData['action']) && $inputData['action'] == 'admin_edit') {
			return Redirect::to('/user/manage')->with('message', '修改成功！');

		}
        return Redirect::to('/user/edit')->with('message', '修改成功！');

    }

    public function postAvatar() {
        if(!Auth::check()) {
            return array('error' => 'not logined');
        }

        $userInfo = Auth::user();

        $user = User::find($userInfo->id);

        $destinationPath = Config::get('app.avatar_upload_path');

        $file = Input::all();

        $rules = array(
            'avatar' => 'mimes:jpeg,bmp,png,gif'
        );

        $validator = Validator::make($file, $rules);
        if($validator->fails()) {
            $messages = $validator->messages();
            return array('error' => $messages->first());
        }

        $file = $file['avatar'];

        $filename_thumb = str_random(32);
        $fileExt = $file->getClientOriginalExtension();

        Image::make($file->getRealPath())->resize('100', null, function($constraint) {
                $constraint->aspectRatio();
            })->save($destinationPath . $filename_thumb . '.' . $fileExt);


        $user->avatar = $filename_thumb . '.' . $fileExt;
        $user->save();

        return array('success'=>'上传成功！');
    }

	public function getManage() {

		if(!Auth::check() || Auth::user()->role != 1) {
			return '没有权限访问!';
		}

		$users = DB::table('users')
						->join('role', 'users.role', '=', 'role.id')
						->select('users.id', 'users.username', 'users.email', 'users.updated_at', 'role.name as role')
						->paginate(20);

		return View::make('front/user_manage')
						->with('users', $users);
	}

	public function getDelete($id) {
		if(!Auth::check() || Auth::user()->role != 1) {
			return '没有权限访问!';
		}

		if($id == 1) {
			return Redirect::to('/user/manage')->with('error', '禁止删除超级管理员！');
		}

		$userInfo = User::find($id);

		return Redirect::to('/user/manage')
					->with('error', '确认要删除 ' . $userInfo->username . ' 吗？')
					->with('userInfo', $userInfo)
					->with('confirm', true);
	}

	public function getConfirmDelete($id){
		if(!Auth::check() || Auth::user()->role != 1) {
			return '没有权限访问!';
		}
		$userInfo = User::find($id);
		$userInfo->delete();

		return Redirect::to('/user/manage')
					->with('message', '用户删除成功！');

	}






}
